package com.lb.dao.redis;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.NonNull;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * Integer 类型 redis 序列化器
 *
 * @author xiemingzhi
 * @since 2.2.0.3
 */
public class IntegerRedisSerializer implements RedisSerializer<Integer> {

    private static final Charset CHARSET = StandardCharsets.UTF_8;

    @Override
    public byte[] serialize(Integer integer) throws SerializationException {
        return (integer == null ? null : String.valueOf(integer).getBytes(CHARSET));
    }

    @Override
    public Integer deserialize(byte[] bytes) throws SerializationException {
        return (bytes == null ? null : Integer.parseInt(new String(bytes, CHARSET)));
    }

    @Override
    public boolean canSerialize(@NonNull Class<?> type) {
        return RedisSerializer.super.canSerialize(type);
    }

    @NonNull
    @Override
    public Class<?> getTargetType() {
        return Integer.class;
    }
}
